/** 
 * @copyright		all rights reserved.
 * @author			how_fly@yahoo.com
 * @brief			user can delete all the schemas
 * 
 * @version			1.0
 * @date
 * 
 * 
 */

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <mysql.h>
#include "del_all_db.h"

/**
 *  @brief delete all the tables in one schema
 *  @param [in]MYSQL: the connection to mysql
 *  @param [in]const char* table: the name of table will be deleted. 
 *  @return int: 0 is good, -1 is error.
 */ 
int delete_db(MYSQL& mysql,const char* table)
{
	char sql[2048] = {0};
	for(int i = 0; i <512; i++) //there are 512 table in each schema
	{
		sprintf(sql, table, i);
		if( mysql_real_query(&mysql, sql, strlen(sql)) )
		{
			printf("error %s %d:%s\n",table,mysql_errno(&mysql),mysql_error(&mysql));
			continue;
		}
	}
	return 0;
}

/**
 *  @brief delete all the tables in one schema
 *  @param [in]MYSQL: the connection to mysql
 *  @param [in]conf_schema:the configure of schema
 *  @param [in]const char* table: the name of table will be deleted. 
 *  @return int: 0 is good, -1 is error.
 */ 
int delete_schema_table(MYSQL& mysql, const conf_schema& _conf_schema, 
						const char* table)
{
	///build connect to mysql
	mysql_init(&mysql);
	if(!mysql_real_connect(&mysql, 
		_conf_schema.host.c_str(),
		_conf_schema.user.c_str(),
		_conf_schema.password.c_str(),
		_conf_schema.name.c_str(), 0, NULL, 0))
	{
		printf("error, connect \n");
		return -1;
	}
	
	///delete all tables in this schema
	if(delete_db(mysql, table) != 0)
	{
		mysql_close(&mysql);
		return -1;
	}
	printf("delete %s is ok\n",table);
	mysql_close(&mysql);
	return 0;
}

int del_all_db(const configure& conf)
{
	MYSQL mysql;
	
	///delete keyword schema
	char keyword_table[] = "drop TABLE KEYWORD_%03d"; 
	delete_schema_table(mysql, conf.keyword, keyword_table);
	
	///delete url schema
	char url_table[] = "drop TABLE URL_%03d"; 
	delete_schema_table(mysql, conf.url, url_table);
	
	///delete pending schema
	char pending_table[] = "drop TABLE PENDING_%03d";
	delete_schema_table(mysql, conf.pending, pending_table);
	
			
	///delete invalid schema
	char invalid_table[] = "drop TABLE INVALID_%03d";
	delete_schema_table(mysql, conf.invalid, invalid_table);
		
			
	///delete dict schema	
	char dict_table[] = "drop TABLE DICT_%03d";
	delete_schema_table(mysql, conf.dict, dict_table);

	return 0;
}
